<template>
        <van-nav-bar title="登录"></van-nav-bar>
      
        <van-form @failed="onFailed" @submit="onSubmit">
          <van-cell-group inset>
            <!-- 通过 pattern 进行正则校验 -->
            <van-field
              label="用户名"
              v-model="username"
              name="username"
              placeholder="请输入用户名"
              :rules="[{ pattern: /\w{3,}/, message: '三位以上 的数字字母下划线' }]"
              required
              :clearable="true"
            />
      
            <van-field
              type="password"
              label="密码"
              v-model="password"
              name="password"
              placeholder="请输入密码"
              :rules="[{ pattern: /.{6,}/, message: '三位以上 的任意字符' }]"
              required
              clearable
            />
          </van-cell-group>
          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit"> 登录 </van-button>
          </div>
        </van-form>
      </template>
      
      <script setup>
      import { ref } from "vue";
      import { loginRequest } from "@/api/user";
      // import router from "@/router";
      import { useRouter } from "vue-router";
      
      import { showSuccessToast, showFailToast } from "vant";
      
      let router = useRouter();
      // /\w{3,}/
      // 三位以上 的数字字母下划线
      let username = ref("");
      let password = ref("");
      
      function onFailed() {
        console.log("onFailed");
      }
      // 表单校验成功就会执行
      async function onSubmit() {
        console.log("onSubmit");
        console.log(username.value);
        console.log(password.value);
        let r = await loginRequest(username.value, password.value);
        console.log(r.data);
        if (r.data.code == 200) {
          // 登录成功
          // token userid 存入本地 --后面可以读取出来使用
          localStorage.setItem("xx-mall-token", r.data.data.token);
          localStorage.setItem("xx-mall-userid", r.data.data.userid);
          router.push("/");
      
          showSuccessToast(r.data.message);
        } else {
          showFailToast(r.data.message);
        }
      }
      </script>
      
      <style></style>
      